integer listener = 0;
key http_request_id;
key avatar;

default
{
    state_entry()
    {
        llSetText("Touch to translate to Pirate Talk", <1,1,1>, 1);
    }
    
    touch_start(integer howmany)
    {
        if (listener == 0)
        {
            avatar = llDetectedKey(0);
            listener = llListen(0, "", avatar, "");
            llSetText("In use by " + llDetectedName(0), <1,0,0>,1);
            llWhisper(0, "Say your sentence; touch to reset");
            llSetTimerEvent(360.0);
        }
        else if (avatar == llDetectedKey(0))
        {
            llResetScript();
        }
        else
            llWhisper(0, "In use");
    }
    
    timer()
    {
        llResetScript();
    }

    listen(integer channel, string name, key id, string message)
    {
        http_request_id = llHTTPRequest("http://pirate.monkeyness.com/cgi-bin/translator.pl?client=monkeyness&bersion=1.2&english=" + llEscapeURL(message), [], "");
    }

    http_response(key request_id, integer status, list metadata, string body)
    {
        if (request_id == http_request_id)
        {
            if (status == 200)
            {
                // The answer will come in XML
                // <pirateAPI>
                //   <pirate>wha' do ye wants landlubber</pirate>
                //   <version>1.2</version>
                // </pirateAPI>    
            
                // "body" contains the string. Search for <pirate> marker:
                integer index = llSubStringIndex(body, "<pirate>");
                if (index != -1)
                {
                    string tempMessage = llGetSubString(body, index + 8, -1);
                    // now check for end marker
                    index = llSubStringIndex(tempMessage, "</pirate>");
                    
                    if (index != -1)
                    {
                        string message = llGetSubString(tempMessage, 0, index - 1);
                    
                        llInstantMessage(avatar, message);
                    }
                    else
                        llInstantMessage(avatar, "Error: </pirate> not found in XML response");
                }
                else
                    llInstantMessage(avatar, "Error: <pirate> not found in XML response");
            }
            else // HTTP Request failed
                llInstantMessage(avatar, "Error " + (string)status + ": " + body);
        }
    }

}